package com.cdf.iapp.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import io.netty.channel.socket.SocketChannel;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import com.cdf.iapp.MainActivity;
import com.cdf.iapp.fragment.MainFrag4;

import android.os.Message;
import android.util.Log;

public class MyClientHandler extends ChannelInboundHandlerAdapter {

	
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel channel = (SocketChannel) ctx.channel();
        System.out.println("信息：已连接远程服务端");
        System.out.println("IP:" + channel.localAddress().getHostString());
        System.out.println("Port:" + channel.localAddress().getPort());
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    	// TODO Auto-generated method stub
    	
    	//断开重连
    	 final EventLoop eventLoop = ctx.channel().eventLoop(); 
         eventLoop.schedule(new Runnable() { 
           @Override 
           public void run() { 
        	 Client client = ClientSingle.getClient();
       		client.create(new Bootstrap(), eventLoop);
           } 
         }, 1L, TimeUnit.SECONDS); 
    	
    	super.channelInactive(ctx);
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //接收msg消息{前面的自定义通道已经解码了}
    	Log.i("log",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 接收到消息：" + msg);
        
        //回调消息
        Message _msg = new Message();
        _msg.what = 0;
        _msg.obj = msg.toString();
        if(MainActivity.mHandler != null){
        	MainActivity.mHandler.sendMessage(_msg );
        }
		
		
		
    }

}


